<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ title }}
      <div class="goback" @click="$router.replace(`/options/homePageList`)">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="120px"
      label-suffix="："
    >
      <el-form-item label="广告类型" prop="type">
        <el-select
          v-model="param.type"
          clearable
          style="width: 400px"
          placeholder="请选择广告类型"
          @change="deleteDeviceConfigAddImage"
        >
          <el-option
            v-for="item in adTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告标题" prop="title">
        <el-input
          v-model="param.title"
          type="text"
          style="width: 400px"
          placeholder="请输入标题"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="宣传图" prop="imageFullPath">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="KNOWLEDGE_IMG"
            :fixed-number="param.type == '0' || param.type == '4' ? [1000, 1334] : param.type == '2' ? [80, 80] : [690, 300]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="flex-c">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            accept=".jpg,.png"
            :data="uploadData"
            :show-file-list="false"
            :on-change="addFileChange"
            :on-success="uploadSuccess"
            :auto-upload="true"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="param.imageFullPath"
              class="file"
              :style="'background-image: url(' + param.imageFullPath + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9 ml10">
            <div>
              建议尺寸：{{
                param.type == "0"|| param.type == '4' ? "1000px X 1334px" : param.type == '2' ? '80px X 80px' : "690px X 300px "
              }}
            </div>
            <div>
              支持png、jpg、jpeg格式，大小不超过2M，上传图片不允许涉及政治敏感与色情
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="关联类型" prop="configId">
        <el-select
          v-model="param.configId"
          style="width: 400px"
          placeholder="请选择关联类型"
          @change="selectType"
        >
          <el-option
            v-for="item in types"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          (param.type != '4' && ( param.configId == 5 ||
            param.configId == 2 ||
            param.configId == 8 ||
            param.configId == 3 ||
            param.configId == 7))|| (param.type == '4' && (
            param.configId == 2 ||
            param.configId == 8 ||
            param.configId == 3))

        "
        label="适用场馆"
        prop="venueIds"
      >
        <el-select
          v-model="param.venueIds"
          multiple
          clearable
          style="width: 400px"
          placeholder="请选择适用场馆"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          param.configId &&
            param.configId != 5 &&
            param.configId != 2 &&
            param.configId != 3 &&
            param.configId != 8 &&
            param.configId != 11 &&
            param.configId != 7
        "
        label="适用场馆"
        prop="venueIds"
      >
        <el-select
          v-model="param.venueIds"
          :multiple-limit="1"
          multiple
          clearable
          style="width: 400px"
          placeholder="请选择适用场馆"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          param.configId &&
            param.configId != 5 &&
            param.configId != 7 &&
            param.configId != 11 &&
            param.configId != 8
        "
        label="关联内容"
        prop="aboutIndex"
      >
        <el-select
          v-model="param.aboutIndex"
          style="width: 400px"
          placeholder="请选择关联内容"
          @change="selectContent"
        >
          <el-option
            v-for="(item, index) in activeList"
            :key="index"
            :label="item[activeName] || item.name"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <!-- 视频号 -->
      <template v-if="param.configId == '7'">
        <el-form-item label="视频号ID" prop="videoNumberId">
          <el-input
            v-model="param.videoNumberId"
            style="width: 400px"
            placeholder="请输入视频号ID"
          />
        </el-form-item>
        <el-form-item style="margin-top: -20px">
          <div class="placeholder9">
            <span>如何获取视频号ID：登录</span>
            <a
              href="https://channels.weixin.qq.com/"
              target="_blank"
              class="primaryColor underline"
            >视频号助手</a>
            <span>，在「首页」中复制视频号ID</span>
          </div>
          <div>
            <el-image
              class="w400"
              :preview-src-list="[
                'https://axure-file.lanhuapp.com/md5__6d903ccf499fd6042fd1a332091bdbfd.png',
              ]"
              src="https://axure-file.lanhuapp.com/md5__6d903ccf499fd6042fd1a332091bdbfd.png"
            />
          </div>
        </el-form-item>
        <el-form-item label="视频ID" prop="videoId">
          <el-input
            v-model="param.videoId"
            style="width: 400px"
            placeholder="请输入视频ID"
          />
        </el-form-item>
        <el-form-item style="margin-top: -20px">
          <div class="placeholder9">
            <span>如何获取视频ID：登录</span>
            <a
              href="https://channels.weixin.qq.com/"
              target="_blank"
              class="primaryColor underline"
            >视频号助手</a>
            <span>，在「动态管理」中复制视频ID</span>
          </div>
          <div>
            <el-image
              class="w400"
              :preview-src-list="[
                'https://axure-file.lanhuapp.com/md5__fe942d7dc67e783dd04aeb849577af58.png',
              ]"
              src="https://axure-file.lanhuapp.com/md5__fe942d7dc67e783dd04aeb849577af58.png"
            />
          </div>
        </el-form-item>
      </template>
      <!-- 专项卡 -->
      <template v-if="param.configId == '8'">
        <el-form-item label="请选择专项卡" prop="paramValue">
          <el-select
            v-model="param.paramValue"
            style="width: 400px"
            placeholder="请选择专项卡"
          >
            <el-option
              v-for="item in activeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </template>
      <el-form-item v-if="param.configId == '11'" label="文本内容" prop="content">
        <!-- <quill-editor ref="myTextEditor" v-model="param.content" placeholder="请输入内容" class="myQuillEditor" :options="quillOption" /> -->
        <WangEditor :value="param.content" @input="e => $set(param, 'content', e)" />
      </el-form-item>
      <el-form-item label="排序码" prop="sort">
        <el-input
          v-model="param.sort"
          style="width: 400px"
          type="number"
          placeholder="请输入排序码"
          maxlength="20"
        />
      </el-form-item>
      <div class="line-style" />
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >提交</el-button>
      </el-form-item></el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import {
  uploadFile,
  bannerSave,
  bannerUpdate,
  bannerDetail,
  venueList,
  bannerConfigInfo,
  SpeailCardList
} from '@/api'
import WangEditor from '@/components/WangEditor'
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Cropper from '@/components/cropper'
export default {
  name: 'HomePageEdit',
  components: {
    Cropper,
    WangEditor,
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      subLoading: false,
      shopId: localStorage.getItem('shopId'),
      uploadFileUrl: uploadFile,
      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      uploadData: {
        folder: 'KNOWLEDGE_IMG',
        type: ''
      },
      venueList: [],
      title: '',
      adTypes: [
        // 0:首页banner，1:新人广告; 广告类型 ,
        { id: '0', name: '场馆首页轮播' },
        { id: '1', name: '新人广告' },
        // { id: '2', name: '首页悬浮广告' },
        { id: '3', name: '商品轮播' },
        { id: '4', name: '商户首页轮播' }
      ],
      queryPath: '',
      param: {
        venueIds: []
      },
      types: [],
      activeList: [],
      rules: {
        imageFullPath: [
          { required: true, message: '请上传宣传图', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文本内容', trigger: 'change' }
        ],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        videoNumberId: [
          { required: true, message: '请输入视频号ID', trigger: 'blur' }
        ],
        videoId: [{ required: true, message: '请输入视频ID', trigger: 'blur' }],
        type: [
          { required: true, message: '请选择广告类型', trigger: 'change' }
        ],
        paramValue: [
          { required: true, message: '请输选择专项卡', trigger: 'change' }
        ],
        info: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        sort: [
          {
            pattern: /^\+?[1-9][0-9]*$/,
            message: '请输入排序码',
            trigger: 'blur'
          }
        ],
        venueIds: [
          { required: true, message: '请选择适用场馆', trigger: 'change' }
        ],
        configId: [
          { required: true, message: '请选择关联类型', trigger: 'change' }
        ]
        // aboutIndex: [
        //   { required: true, message: '请选择关联内容', trigger: 'change' }
        // ]
      },
      edit: false,
      cgList: [],
      id: ''
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.$route.meta.title = '编辑首页广告'
      this.title = '编辑首页广告'
      this.id = this.$route.query.id
      this.edit = true
      this.getData()
    } else {
      this.$route.meta.title = '新增首页广告'
      this.title = '新增首页广告'
      this.getConfigInfo()
    }
    venueList({
      param: {}
    })
      .then((res) => {
        if (res.errorCode !== '000000') return
        this.venueList = res.recordList
      })
      .catch(() => {})
  },
  methods: {
    getData() {
      bannerDetail({ param: { id: this.id }})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.param = res.record
            sessionStorage.setItem('venueId', res.record.venueIds[0])
            bannerConfigInfo({ param: {}})
              .then((resb) => {
                if (resb.errorCode === '000000') {
                  this.types = resb.record
                  this.types.forEach((item) => {
                    if (item.id === this.param.configId) {
                      this.activeName = item.nameKey
                      this.queryPath = item.queryPath
                      this.param.idKey = item.idKey
                      this.activeName = item.nameKey
                      this.param.jumpPath = item.jumpPath
                      if (item.jumpPath) {
                        this.getActive()
                      }
                    }
                  })
                }
              })
              .catch((err) => {
                console.log(err)
              })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getConfigInfo() {
      bannerConfigInfo({})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.types = res.record
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    selectVenue(v) {
      this.activeList = []
      this.$set(this.param, 'paramValue', '')
      this.param.paramName = ''
      this.$set(this.param, 'aboutIndex', '')
      sessionStorage.setItem('venueId', v)
      // if (this.param.configId == 8) {
      //   SpeailCardList({ param: { status: 0 }}).then(res => {
      //     this.activeList = res.recordList
      //   })
      // }

      if (this.param.jumpPath) {
        this.getActive()
      }
    },
    fwbChange(e) {
      this.$set(this.param, 'content', e)
    },
    selectType(id) {
      this.activeList = []
      this.$set(this.param, 'paramValue', '')
      this.param.paramName = ''
      this.$set(this.param, 'venueIds', [])
      const item = this.types.find((item) => item.id === id)
      this.activeName = item.nameKey
      this.param.idKey = item.idKey
      this.param.jumpPath = item.jumpPath
      this.queryPath = item.queryPath
      this.$refs.ruleForm.clearValidate()
      // if (!this.param.venueId) {
      //   this.$message.error('请先选择场馆')
      //   return
      // }
      if (item.jumpPath && id === 8) {
        this.getActive()
      }
      if (id === 10) {
        this.getActive()
      }
      if (item.jumpPath && this.param.venueIds.length === 1) {
        this.getActive()
      }
    },
    getActive() {
      if (
        !(this.param && this.param.venueIds && this.param.venueIds.length > 0)
      ) {
        return false
      }
      request({
        url: `/do?c=${this.queryPath}`,
        method: 'POST',
        data: {
          param: {
            venueId: this.param.venueIds.join(','),
            stadiumId: this.param.venueIds.join(','),
            courseStatus: '2',
            status: '1',
            saleType: this.param.configId === 10 ? '0' : '',
            type: '1',
            flag: this.param.configId === 6 ? '2' : '1',
            saleStatus: '1'
          }
        }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            this.activeList = res.recordList
            if (this.queryPath === '411006') {
              const now = +new Date().getTime()
              this.activeList = res.recordList.filter((item) => {
                const end = +new Date(item.saleDateEnd).getTime()
                return end > now
              })
            }
            this.activeList.forEach((item, index) => {
              if (item[this.param.idKey] === this.param.paramValue) {
                // this.param.aboutIndex = index
                this.$set(this.param, 'aboutIndex', index)
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    selectContent(index) {
      // console.log(index);
      const item = this.activeList[index]
      // console.log(item);
      this.param.paramValue = item[this.param.idKey] ?? item.id
      this.param.paramName = item[this.activeName] ?? item.name
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (this.param.type !== '1') return
      if (res.success) {
        this.$set(this.param, 'imageFullPath', res.showUrl)
        this.$set(this.param, 'pathUrl', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'imageFullPath', config.showUrl)
        this.$set(this.param, 'pathUrl', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      if (this.param.type === '1') return
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      // this.$set(this.param, 'img2', '')
      this.$set(this.param, 'pathUrl', '')
      this.$set(this.param, 'imageFullPath', '')
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.param }
          // if (param.configId !== 5) {
          //   param.venueIds = [param.venueId]
          // }
          if ((param.configId !== 5 && param.configId !== 11) && param.venueIds.length === 0) {
            this.$message.error('请先选择场馆')
            return
          }
          this.subLoading = true
          if (this.edit) {
            bannerUpdate({
              param
            })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('提交成功')
                  this.$router.replace(`/options/homePageList?renovate=1`)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            param.status = '1'
            bannerSave({
              param
            })
              .then((res) => {
                this.subLoading = false
                if (res.errorCode === '000000') {
                  this.$message.success('提交成功')
                  this.$router.replace(`/options/homePageList?renovate=1`)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
